<?php
require_once('kernel.inc');

if($AUTH->logedstatus == true && $AUTH->permission == 'system')
{
   require_once(LIBRARIES.'/links.inc');
   $LINKS = new links($DB, $MECCANO);
   $SMARTY->assign_by_ref('allow_tree', $LINKS->params['tree']);

   /**
     * Check - whether the tree, and transfer of a tree is authorized
     */
   if($LINKS->params['tree'] == true)
   {
      $MECCANO->SetParams("order=desc;root=hide");
      $SMARTY->assign('tree', $MECCANO->GetLeaves(false, 'links', $lang));
   }


   /**
     * Delete of links
     */
   if(isset($_REQUEST['dele']))
   {
      $LINKS->Delete($_REQUEST['dele']);
      SmartyPaginate::reset($_SYS['meccano']['pid']);
      SmartyPaginate::setLimit($MECCANO->system['items'], $_SYS['meccano']['pid']);
      SmartyPaginate::setPageLimit($MECCANO->system['pages'], $_SYS['meccano']['pid']);
   }

	/**
	* ACTIONS
	* 1 = Add link
	* 2 = Edit link
	*/
   switch ($action)
   {
      // Edit link
      case 2:
      $vars = $LINKS->View($id);
      $SMARTY->assign('vars', $vars);

      // Add or Save Edited link
      case 1:
      if($submit != false)
      {
         $input = $_REQUEST['link'];
//       isUrl($input['link']);
         prepare_str($input['link']);
         isEmail($input['email']);

         if($LINKS->params['tree'] == false) $input['cat'] = null;
         if(!in_array(strtolower($input['lang']), $MECCANO->system['lang'])) $input['lang'] = $MECCANO->system['lang'][0];

         if($id !== false)
         {
            $LINKS->Update($id, $input);
         } else
         {
            $LINKS->Add($input);
         }

         if($LINKS->error != false)
         {
            $SMARTY->assign('error', $LINKS->error);
            $SMARTY->assign('vars', $_REQUEST);
         } else
         {
            $SMARTY->assign('make', true);
         }
      }

      $SMARTY->display('admin.editlink.tpl.html');

      break;

      default:

      $vars = $LINKS->Get();
      if($vars)
      {
         SmartyPaginate::setTotal(count($vars), $_SYS['meccano']['pid']);
         SmartyPaginate::setUrl($_SERVER['PHP_SELF'], $_SYS['meccano']['pid']);
         $SMARTY->assign('vars', array_slice($vars, SmartyPaginate::getCurrentIndex($_SYS['meccano']['pid']), SmartyPaginate::getLimit($_SYS['meccano']['pid'])));
         SmartyPaginate::assign($SMARTY, 'paginate', $_SYS['meccano']['pid']);
      } else
      {
         $SMARTY->assign('vars', false);
      }
      $SMARTY->display('admin.links.tpl.html');
   }
} else
{
   echo $AUTH->frame_redirector();
}
?>